package items;

import shopping.manager.R;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import date.base.DbHelper;

public class editItem extends Activity {
	
	private DbHelper DbHelper;
	private Long ItemRowId;
	private String TableName;
	
	private AutoCompleteTextView ItemName;
	private EditText Quantity;
	private EditText Price;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item_edit);
		DbHelper = new DbHelper(this);
		DbHelper.open();
		
		Bundle extras = getIntent().getExtras();
		ItemRowId = extras.getLong(DbHelper.ITEM_ROWID);
		TableName = extras.getString(DbHelper.ITEM_TABLE_NAME);
		
		ItemName = (AutoCompleteTextView) findViewById(R.id.NameEditText);
		Quantity = (EditText) findViewById(R.id.QuantityEditText);
		Quantity.setSelectAllOnFocus(true);
		Price = (EditText) findViewById(R.id.PriceEditText);
		Price.setSelectAllOnFocus(true);
		
		Button b = (Button) findViewById(R.id.ConfirmButton);
		
		populatefields();
		
		b.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(ItemName.getText().toString().length() == 0){
					Toast.makeText(editItem.this, "You must provide an input", Toast.LENGTH_SHORT).show();
				}
				else{
					saveItemData();
					finish();
				}
			}
		});
	}

	private void populatefields() {
		Cursor item = DbHelper.getItem(TableName, ItemRowId);
		
		ItemName.setText(item.getString(item.getColumnIndexOrThrow(DbHelper.ITEM_NAME)));
		Quantity.setText(item.getString(item.getColumnIndexOrThrow(DbHelper.ITEM_QUANTITY)));
		Price.setText(item.getString(item.getColumnIndexOrThrow(DbHelper.ITEM_VALUE)));
	}
	
	private void saveItemData() {
		String item_name = ItemName.getText().toString();
		String quantity_text = Quantity.getText().toString();
		double quantity = 0;
		if(quantity_text.length() > 0) {
			quantity = Double.valueOf(quantity_text);
		}
		String price_text = Price.getText().toString();
		double price = 0;
		if(price_text.length() > 0) {
			price = Double.valueOf(price_text);
		}
		double totalPrice =(double) (Math.round(quantity*price*100))/100;
		
		item_data itemData = new item_data(TableName, ItemRowId, item_name, price, quantity, totalPrice);
		
		DbHelper.updateItem(itemData);
	}

}
